package com.money.tracker.common.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.money.tracker.common.entity.BaseEntity;
import com.money.tracker.common.enums.IResponseEnum;
import com.money.tracker.common.exception.MoneyTrackerBizException;
import com.money.tracker.common.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
public class MoneyTrackerObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                LocalDateTime current = ObjectUtil.isNotNull(baseEntity.getCreateTime()) ? baseEntity.getCreateTime() : LocalDateTime.now();
                baseEntity.setCreateTime(current);
                baseEntity.setUpdateTime(current);
                Long userId = Objects.nonNull(baseEntity.getCreateBy()) ? baseEntity.getCreateBy() : LoginUtil.getUserId();
                baseEntity.setCreateBy(userId);
                baseEntity.setUpdateBy(userId);
                baseEntity.setDelFlag(0);
            }
        } catch (Exception e) {
            throw new MoneyTrackerBizException(IResponseEnum.DATA_FILL_ANOMALIES);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                baseEntity.setUpdateTime(LocalDateTime.now());
                baseEntity.setUpdateBy(LoginUtil.getUserId());
            }
        } catch (Exception e) {
            throw new MoneyTrackerBizException(IResponseEnum.DATA_FILL_ANOMALIES);
        }
    }

}